package com.lzy.conf;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import springfox.documentation.annotations.ApiIgnore;

/**
 * description: HttpErrorController ()<br>
 * date: 2020-12-1 19:04 <br>
 * author: lcc <br>
 * version: 1.0 <br>
 */
@Slf4j
@RestController
@ApiIgnore
public class HttpErrorController implements ErrorController {
    private final static String ERROR_PATH = "/error";
    private ErrorAttributes errorAttributes;

    @Autowired
    public HttpErrorController(ErrorAttributes errorAttributes) {
        this.errorAttributes = errorAttributes;
    }

    @RequestMapping(value = ERROR_PATH)
    @ResponseBody
    @ExceptionHandler(value = {Exception.class})
    public JSONResult error(final WebRequest req){
        Throwable error = this.errorAttributes.getError(req);
        return JSONResult.errorMsg(error.getMessage());
    }
}
